package com.atguigu.tingshu.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.model.user.UserListenProcess;
import com.atguigu.tingshu.user.service.UserListenProcessService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.user.UserListenProcessVo;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@SuppressWarnings({"all"})
public class UserListenProcessServiceImpl implements UserListenProcessService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private RabbitService rabbitService;

    @Override
    public Map<String, Object> getLatelyTrack(Long userId) {
        //构造返回值
        Map<String, Object> stringObjectHashMap = new HashMap<>();
        //数据存在moongodb中
        //构建集合名称
        String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
        //构建查询条件
        Query query = new Query();
        query.with(Sort.by(Sort.Direction.DESC,"updateTime")).limit(1);
        //查询返回值
        UserListenProcess listenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
        //封装返回值
        stringObjectHashMap.put("albumId",listenProcess.getAlbumId());
        stringObjectHashMap.put("trackId",listenProcess.getTrackId());
        //返回数据
        return stringObjectHashMap;
    }

    @Override
    public void updateListenProcess(Long userId, UserListenProcessVo userListenProcessVo) {
        //构建集合名称
        String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
        //获取数据
        Query query = Query.query(Criteria.where("trackId").is(userListenProcessVo.getTrackId()));
        UserListenProcess listenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
        //判断获取的数据是不是空的
        if (null != listenProcess) {
            //不为空，说明数据库有了，就进行数据的覆盖
            listenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
            listenProcess.setUpdateTime(new Date());
        } else {
            //没有数据就新建一个
            listenProcess = new UserListenProcess();
            //赋值：
            listenProcess.setUserId(userId);
            listenProcess.setTrackId(userListenProcessVo.getTrackId());
            listenProcess.setAlbumId(userListenProcessVo.getAlbumId());
            listenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
            listenProcess.setCreateTime(new Date());
            listenProcess.setUpdateTime(new Date());
        }
        //保存数据
        mongoTemplate.save(listenProcess,collectionName);

        //防止恶意刷播放量，使用分布式锁的思想
        //构建放进去的key
        String redisKey = userId +":" + userListenProcessVo.getTrackId();
        //先去redis里放数据，能放进去说明第一次听，相应的统计加一，放不进去就不管了
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(redisKey, 1, 24, TimeUnit.HOURS);
        if (ifAbsent){
            TrackStatMqVo trackStatMqVo = new TrackStatMqVo();
            trackStatMqVo.setCount(1);
            trackStatMqVo.setStatType(SystemConstant.TRACK_STAT_PLAY);
            trackStatMqVo.setTrackId(listenProcess.getTrackId());
            trackStatMqVo.setAlbumId(listenProcess.getAlbumId());
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            trackStatMqVo.setBusinessNo(uuid);
            rabbitService.sendMessage(
                    MqConst.EXCHANGE_TRACK,
                    MqConst.ROUTING_TRACK_STAT_UPDATE,
                    JSON.toJSONString(trackStatMqVo)
            );
        }

    }

    @Override
    public BigDecimal getTrackBreakSecond(Long userId, Long trackId) {
        //组合名称集合
        String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
        //从mogon中查询当前声音的信息
        //构建查询条件
        Query query = Query.query(Criteria.where("trackId").is(trackId));
        //查询
        UserListenProcess listenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
        //不为空就返回listenProcess的时间
        if (null != listenProcess) {
            return listenProcess.getBreakSecond();
        }
        return new BigDecimal(0.00);
    }
}
